﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ThousandFunClient.model;
using ThousandFunClient.Util;
using System.Collections;
using System.IO.Ports;
using System.Timers;
using log4net;

namespace ThousandFunClient.Util
{
    class DataUtil
    {

        //byte[] array = new byte[1];
        //    array[0] = (byte)(Convert.ToInt32(ASCII码)); //ASCII码强制转换二进制
        //    转换后的字母= Convert.ToString(System.Text.Encoding.ASCII.GetString(array));
        //返回true表示通过检验
        public static bool verifyData(byte[] buf)
        {
            bool ret = true;

            if (buf == null) return false;

            if(!buf[0].Equals(0)||buf.Length<6)
            {
                ret = false;
            }

            if (ret)
            {
                if (!buf[2].Equals(1))
                {
                    ret = false;
                }
                if (!buf[3].Equals(2))
                {
                    ret = false;
                }
                if (!buf[4].Equals(139))
                {
                    ret = false;
                }

                if (buf.Length != buf[1] + 3)
                {
                    ret = false;
                }
            }

            Constants.syslogger.Debug("verifyData:");
            Constants.syslogger.Debug(buf);
            Constants.syslogger.Debug(ret);
            return ret;
        }

        public static byte[] convertPortCSendDataBytes(String CMD)
        {
            CMD = CMD.Trim();
            String[] tc = CMD.Split(' ');
            byte[] tg = new byte[tc.Length];
            for (int i = 0; i < tc.Length; i++)
            {
                tg[i] = (byte)int.Parse(tc[i]);
            }
            return tg;
        }

        public static byte[] convertSendDataBytes(String CMD)
        {
            int[] bs = convertSendDataInt(CMD);
            byte[] bsb = new byte[bs.Length];
            for (int i = 0; i < bs.Length; i++)
            {

                bsb[i] = (byte)bs[i];
            }
            return bsb;
        }
        public static int[] convertSendDataInt(String CMD)
        {
            CMD = CMD.Trim();
            String[] tc = CMD.Split(' ');
            int[] tg = new int[tc.Length];
            for (int i = 0; i < tc.Length; i++)
            {
                tg[i] = Convert.ToInt32(tc[i], 16);
            }


            return tg;
        }


        public static byte[] byteAdd(byte[] temp1, byte[] temp2)
        {
            //byte[]   temp1   =   new   byte[100]; 
            //byte[]   temp2   =   new   byte[50]; 
            if (temp1 == null)
            {
                return byteCopy(temp2);
            }
            byte[]   bt   =   new   byte[temp1.Length   +   temp2.Length]; 
            Buffer.BlockCopy(temp1,   0,   bt,   0,   temp1.Length); 
            Buffer.BlockCopy(temp2,   0,   bt,   temp1.Length,   temp2.Length);
            return bt;
        }

        public static byte[] byteCopy(byte[] temp1)
        {
            byte[] bt = new byte[temp1.Length];
            Buffer.BlockCopy(temp1, 0, bt, 0, temp1.Length);
            return bt;
        }
        
        public static String[] convertSendData(String CMD)
        {
            String[] tc = CMD.Split(' ');
            String[] tg = new String[tc.Length];
            for (int i = 0; i < tc.Length; i++)
            {
                tg[i] = Convert.ToInt32(tc[i], 16).ToString();
            }


            return tg;
        }

        //preBatchDataSuccess.CycleNum = nowBatchData.CycleNum;

        public static bool sendDatePortB(BatchData batchData, SerialPort sp_Send)
        {
            PortUtil.OpenCOM(sp_Send);
            sp_Send.Write(batchData.toSendStr());

            return true;
        }

        public static bool isBatchDataOK(BatchData batchData)
        {
            if(batchData.AngleValue==null)
            {
                return false;
            }

            if (batchData.TorqueValue == null)
            {
                return false;
            }

            //if (batchData.ProgramStepValue == null)
            //{
            //    return false;
            //}

            //if (batchData.PMStatusValue== null)
            //{
            //    return false;
            //}

            //if (batchData.ProgramNoValue == null)
            //{
            //    return false;
            //}

            return true;
        }

        public static bool isBatchDataEnd(BatchData batchData)
        {
            if (batchData.AngleValue == null)
            {
                return false;
            }

            if (batchData.TorqueValue == null)
            {
                return false;
            }

            if (batchData.ProgramStepValue == null)
            {
                return false;
            }

            if (batchData.PMStatusValue == null)
            {
                return false;
            }

            if (batchData.ProgramNoValue == null)
            {
                return false;
            }

            return true;
        }

        public static String convertSendDataStr(String CMD)
        {
            String[] tg = convertSendData(CMD);
            string ret = "";
            for (int i = 0; i < tg.Length; i++)
            {
                ret = ret + tg[i];
            }

            return ret;
        }


        public static String formatDisStr(String disStr,int strlength)
        {
            int pointi = 100000;
            double d = Double.Parse(disStr);
            double dlarge = d* pointi;
            string slarge = d.ToString();
            string t = slarge.Substring(0, strlength);

            string nextt = slarge.Substring(strlength, strlength+1);
            int inext = int.Parse(nextt);

            if (inext > 4)
            {
                double td = Double.Parse(t) + 1;
                t = td.ToString();
            }

            for (int i=1; i < slarge.Length - strlength; i++)
            {
                t = t + "0";
            }
            double finalt = Double.Parse(t);
            string ret = (finalt / pointi).ToString();


            return ret;
        }

        public static String formatDisStr(double doubledisStr)
        {
            
            //将转换后的Double型扭矩值，格式化为0.000, 0.001, 0.012, 0.123, 1.234, 12.34, 123.4, 1234 这样的格式。目前存在的问题是0.000被显示为0
            //0.100被显示为0.1，0.120被显示为0.12。

            // 20121229已更正上述错误：可正确显示0.000, 1.000, 12.00, 123.0, 1234, 0.010, 0.100。如有更多未考虑情况再更新代码。可将btn_TestOnly按钮显示出来测试
            
            string disStr =doubledisStr.ToString();


            if (disStr.IndexOf('.') > 0 && disStr.IndexOf('.') < 4)
            {
                doubledisStr = Math.Round(doubledisStr, 4 - disStr.IndexOf('.'));
            }
            else
            {
                doubledisStr = Math.Round(doubledisStr, 0);
            }

           
            
            disStr = doubledisStr.ToString();

            string ret = "";
            if (disStr.IndexOf('.') > 0 && disStr.IndexOf('.') < 4)
            {

                ret = disStr.Substring(0, disStr.Length > 5 ? 5 : disStr.Length);
                
                
            }
            else
            {
                ret = disStr.Substring(0, disStr.Length > 4 ? 4 : disStr.Length);
            }

            int retl = ret.Length;
            if (ret.IndexOf('.') > 0)
            {
                for (int i = 0; i < 5 - retl; i++)
                {
                    ret = ret + "0";
                }
            }
            else
            {
                if (retl < 4)
                {
                    ret += ".";
                }
                for (int i = 0; i < 4 - retl; i++)
                {
                    ret = ret + "0";
                }
            }

            return ret;
        }


        
        public static TFModel parseReceiveint(byte[] realyrec)
        {
            
            TFModel tfmodel = new TFModel();
            tfmodel.Startbyte = fillhex(inttohex((int)realyrec[0]));
            tfmodel.LOProtocol = fillhex(inttohex((int)realyrec[1]));
            tfmodel.DOCommand = fillhex(inttohex((int)realyrec[2]));
            tfmodel.SOCommand = fillhex(inttohex((int)realyrec[3]));
            tfmodel.Separator = fillhex(inttohex((int)realyrec[4]));
            tfmodel.DataType = fillhex(inttohex((int)realyrec[5]));

            
            int len = Int32.Parse(tfmodel.LOProtocol);
            //目前先按照data长度等于总长度减4处理
            int datalen = len - 4;

            for (int i = 6 ; i < 6 + datalen; i++)
            {
                tfmodel.AnswerdataLog = tfmodel.AnswerdataLog + fillhex(inttohex((int)realyrec[i]));
            }

            for (int i = 5 + datalen; i > 5; i--)
            {
                tfmodel.Answerdata = tfmodel.Answerdata + fillhex(inttohex((int)realyrec[i]));
            }
            tfmodel.Checksum = inttohex((int)realyrec[5 + datalen + 1]);

            return tfmodel;
        }

        private static string fillhex(string source)//主要方法
        {
            if (source.Length < 2)
            {
                return "0" + source;
            }
            else
            {
                return source;
            }
        }

        public static TFModel parseReceive(String receive)
        {
            String[] realyrec = receive.Split(' ');
            TFModel tfmodel = new TFModel();
            tfmodel.Startbyte = realyrec[0];
            tfmodel.LOProtocol = realyrec[1];
            tfmodel.DOCommand = realyrec[2];
            tfmodel.SOCommand = realyrec[3];
            tfmodel.Separator = realyrec[4];
            tfmodel.DataType = realyrec[5];

            int len = Int32.Parse(tfmodel.LOProtocol);
            int cc = tfmodel.SOCommand.Length;
            //目前先按照data长度等于总长度减4处理
            int datalen = len -4;
            for (int i = 5+datalen; i > 5; i--)
            {
                tfmodel.Answerdata = tfmodel.Answerdata + realyrec[i];
            }
            tfmodel.Checksum = realyrec[5 + datalen + 1];

            return tfmodel;
        }
        private static string specinttostring(int source)//被主要方法调用的一个辅助方法
        {
            if (source < 10)
            {
                return source.ToString();
            }
            else
            {
                switch (source)
                {
                    case 10:
                        return "a";
                    case 11:
                        return "b";
                    case 12:
                        return "c";
                    case 13:
                        return "d";
                    case 14:
                        return "e";
                    case 15:
                        return "f";
                    default:
                        return "";
                }
            }
        }


        public static string inttohex(int source)//主要方法
    {
        if(source <10)
        {
            return source.ToString();
        }
        else if (source <=15)
        {
            return specinttostring(source);
        }
        else
        {
            int raisenum = 16;
            int addnum = 16;
            int positionnum = 1;
            while((source - addnum) >= 0)
            {
                positionnum++;
                addnum = addnum * raisenum;
            }
            int[] valuepositionnum = new int[positionnum];
            for(int i = 0;i<positionnum;i++)
            {
                valuepositionnum[i] = 0;
            }

            int[] valueaddnum = new int[positionnum];

            for(int i = 0;i<positionnum;i++) 
            {
                valueaddnum[i] = Convert.ToInt32(Math.Pow(raisenum,i));
            }

int[] decreasesource = new int[positionnum];

decreasesource[positionnum -1] = source;

for(int i = positionnum -1;i>=0;i--)

{

while((decreasesource[i] - valueaddnum[i] ) >=0)

{

if(i != 0)

decreasesource[i -1] = decreasesource[i] - valueaddnum[i] ;

valuepositionnum[i]++;

valueaddnum[i] = valueaddnum[i] + Convert.ToInt32(Math.Pow(raisenum, i));

}

}

string[] stringvaluepositionnum = new string[positionnum];

for (int i = 0; i < positionnum; i++) 

{

stringvaluepositionnum[i] = specinttostring(valuepositionnum[i]);

}

string result = "";

for(int i = positionnum -1;i>=0;i--)

{

result = result + stringvaluepositionnum[i];

}

return result;
}

}

    }
}
